<template>
  <div class="page">
    <div class="toolbar">
      <el-form :inline="true" class="filters">
        <el-form-item label="版本">
          <el-select v-model="currentVersionId" placeholder="选择版本" @change="reloadTree" style="width:220px">
            <el-option v-for="v in versions" :key="v.id" :label="v.name + ' (' + v.version_code + ')'" :value="v.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openCreateVersion">新增版本</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openEditVersion" :disabled="!currentVersionId">编辑版本</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="openUploadDialog" :disabled="!currentVersionId">上传Excel（覆盖）</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="reloadTree">刷新</el-button>
        </el-form-item>
      </el-form>
      <div class="version-summary">
        <div class="vs-row">
          <span class="vs-label">当前版本：</span>
          <span class="vs-name">{{ currentVersion?.name || '-' }}</span>
          <span class="vs-code" v-if="currentVersion">({{ currentVersion.version_code }})</span>
        </div>
        <div class="vs-row">
          <span class="vs-label">适用类型：</span>
          <template v-if="currentVersion?.activity_types && currentVersion.activity_types.length">
            <el-tag v-for="t in currentVersion.activity_types" :key="t.id" size="small" style="margin-right:6px">{{ t.name }}</el-tag>
          </template>
          <span v-else class="vs-empty">未设置</span>
          <el-button size="small" type="primary" link @click="openEditVersion">设置</el-button>
        </div>
      </div>
    </div>

    <div class="content">
      <div class="left">
        <el-input v-model="keyword" placeholder="搜索名称/编码" clearable @input="applyFilter" style="margin-bottom:8px" />
        <el-tree ref="treeRef" :data="tree" node-key="id" :props="treeProps" draggable :allow-drop="allowDrop" @node-click="onNodeClick" @node-drop="onNodeDrop">
          <template #default="{ node, data }">
            <div style="display:flex;align-items:center;justify-content:space-between;width:100%">
              <span>{{ node.label }}</span>
              <el-dropdown v-if="data.type==='dimension' || data.type==='theme'">
                <span class="el-dropdown-link">...</span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openEditFromNode(data)">修改</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="right">
        <div v-if="selectedThemeId">
          <div class="table-toolbar">
            <el-button @click="allocateCodesForTheme">为无编码项分配编码</el-button>
            <el-button type="primary" @click="saveItemEdits" :loading="saving">保存改动</el-button>
          </div>
          <el-table :data="items" style="width:100%">
            <el-table-column prop="name" label="名称" min-width="220">
              <template #default="{ row }"><el-input v-model="row.name" /></template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120">
              <template #default="{ row }">
                <el-select v-model="row.category" style="width:100%">
                  <el-option label="基本" value="basic" />
                  <el-option label="扣分" value="deduct" />
                  <el-option label="否决" value="veto" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="criteria" label="评定标准说明" min-width="280">
              <template #default="{ row }"><el-input v-model="row.criteria" type="textarea" autosize /></template>
            </el-table-column>
            <el-table-column prop="weight" label="权重" width="120">
              <template #default="{ row }"><el-input v-model.number="row.weight" type="number" /></template>
            </el-table-column>
            <el-table-column prop="deduct_value" label="扣分值" width="120">
              <template #default="{ row }"><el-input v-model.number="row.deduct_value" type="number" /></template>
            </el-table-column>
            <el-table-column prop="veto_flag" label="否决" width="100">
              <template #default="{ row }"><el-switch v-model="row.veto_flag" /></template>
            </el-table-column>
            <el-table-column prop="order_index" label="排序" width="100">
              <template #default="{ row }"><el-input v-model.number="row.order_index" type="number" /></template>
            </el-table-column>
            <el-table-column prop="code" label="编码" width="140">
              <template #default="{ row }">
                <div style="display:flex;gap:8px;align-items:center">
                  <span>{{ row.code || '-' }}</span>
                  <el-button size="small" @click="allocateCodeForItem(row)" :disabled="!!row.code">获取</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="placeholder">选择左侧主题查看其指标项</div>
      </div>
    </div>

    <el-dialog v-model="showVersionDialog" title="新增版本" width="520px" destroy-on-close>
      <el-form :model="versionForm" label-width="100px">
        <el-form-item label="版本编码"><el-input v-model="versionForm.version_code" /></el-form-item>
        <el-form-item label="版本名称"><el-input v-model="versionForm.name" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showVersionDialog=false">取消</el-button>
        <el-button type="primary" @click="createVersion">创建</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showVersionEditDialog" title="编辑版本" width="520px" destroy-on-close>
      <el-form :model="versionEditForm" label-width="100px">
        <el-form-item label="版本编码"><el-input v-model="versionEditForm.version_code" /></el-form-item>
        <el-form-item label="版本名称"><el-input v-model="versionEditForm.name" /></el-form-item>
        <el-form-item label="适用活动类型">
          <el-select v-model="versionEditForm.activity_type_ids" multiple placeholder="选择适用类型" style="width:100%">
            <el-option v-for="opt in activityTypeOptions" :key="opt.id" :label="opt.name" :value="opt.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showVersionEditDialog=false">取消</el-button>
        <el-button type="primary" @click="saveEditVersion">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showUploadDialog" title="上传指标模板（覆盖导入）" width="560px" destroy-on-close>
      <div style="margin-bottom:12px">当前版本：{{ currentVersionName }}</div>
      <input type="file" accept=".xlsx" @change="onFileChange" />
      <template #footer>
        <el-button @click="showUploadDialog=false">取消</el-button>
        <el-button type="primary" :disabled="!uploadFile" @click="confirmUpload">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showDimensionEditDialog" title="编辑一级指标" width="520px" destroy-on-close>
      <el-form :model="{ name: dimensionEditName }" label-width="100px">
        <el-form-item label="名称"><el-input v-model="dimensionEditName" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDimensionEditDialog=false">取消</el-button>
        <el-button type="primary" @click="saveDimensionName">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showThemeEditDialog" title="编辑二级指标" width="520px" destroy-on-close>
      <el-form :model="{ name: themeEditName }" label-width="100px">
        <el-form-item label="名称"><el-input v-model="themeEditName" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showThemeEditDialog=false">取消</el-button>
        <el-button type="primary" @click="saveThemeName">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { api } from '../../api/client'

type Version = { id: string; version_code: string; name: string; activity_types?: { id: string; code: string; name: string }[] }
type Dimension = { id: string; name: string; order_index: number; aggregated_weight?: number; aggregated_deduct?: number }
type Theme = { id: string; name: string; order_index: number; dimension_id: string; aggregated_weight?: number; aggregated_deduct?: number }
type Item = { id: string; name: string; category: string; weight?: number|null; deduct_value?: number|null; veto_flag: boolean; order_index: number; code?: string|null; criteria?: string|null }

const versions = ref<Version[]>([])
const currentVersionId = ref<string>('')
const keyword = ref('')
const tree = ref<any[]>([])
const treeRef = ref<any>()
const treeProps = { children: 'children', label: 'name' }
const selectedThemeId = ref<string>('')
const selectedDimensionId = ref<string>('')
const dimensionEditName = ref('')
const themeEditName = ref('')
const items = ref<Item[]>([])
const saving = ref(false)

const showVersionDialog = ref(false)
const versionForm = reactive({ version_code: '', name: '' })
const showVersionEditDialog = ref(false)
const versionEditForm = reactive({ version_code: '', name: '', activity_type_ids: [] as string[] })
const activityTypeOptions = ref<{ id: string; code: string; name: string }[]>([])
const showUploadDialog = ref(false)
const uploadFile = ref<File | null>(null)
const showDimensionEditDialog = ref(false)
const showThemeEditDialog = ref(false)
const currentVersion = computed(() => versions.value.find(x => x.id === currentVersionId.value) || null)
const currentVersionName = computed(() => currentVersion.value ? `${currentVersion.value.name} (${currentVersion.value.version_code})` : '-')

function openCreateVersion() { showVersionDialog.value = true }

async function createVersion() {
  if (!versionForm.version_code || !versionForm.name) return
  const resp = await api.post('/indicators/versions', { version_code: versionForm.version_code, name: versionForm.name })
  versions.value.push({ id: resp.data.id, version_code: resp.data.version_code, name: resp.data.name })
  currentVersionId.value = resp.data.id
  showVersionDialog.value = false
  await reloadTree()
}

async function loadVersions() {
  const resp = await api.get('/indicators/versions')
  versions.value = resp.data
  if (!currentVersionId.value && versions.value.length) currentVersionId.value = versions.value[0].id
}

function openEditVersion() {
  if (!currentVersionId.value) return
  const v = versions.value.find(x => x.id === currentVersionId.value)
  if (!v) return
  versionEditForm.version_code = v.version_code
  versionEditForm.name = v.name
  versionEditForm.activity_type_ids = (v.activity_types || []).map(x => x.id)
  showVersionEditDialog.value = true
}

async function saveEditVersion() {
  if (!currentVersionId.value) return
  await api.patch(`/indicators/versions/${currentVersionId.value}`, { version_code: versionEditForm.version_code, name: versionEditForm.name, activity_type_ids: versionEditForm.activity_type_ids })
  const v = versions.value.find(x => x.id === currentVersionId.value)
  if (v) { v.version_code = versionEditForm.version_code; v.name = versionEditForm.name; v.activity_types = activityTypeOptions.value.filter(o => versionEditForm.activity_type_ids.includes(o.id)) }
  showVersionEditDialog.value = false
}

async function reloadTree() {
  if (!currentVersionId.value) return
  const dims: Dimension[] = (await api.get('/indicators/dimensions', { params: { version_id: currentVersionId.value } })).data
  const nodes: any[] = []
  for (const d of dims.sort((a,b)=>a.order_index-b.order_index)) {
    const themes: Theme[] = (await api.get('/indicators/themes', { params: { dimension_id: d.id } })).data
    const tnodes: any[] = []
    for (const t of themes.sort((a,b)=>a.order_index-b.order_index)) {
      // 为主题构建显示名称，包含聚合分数
      let themeDisplayName = t.name
      if (t.aggregated_weight !== undefined && t.aggregated_weight > 0) {
        themeDisplayName += ` (${t.aggregated_weight}分)`
      }
      if (t.aggregated_deduct !== undefined && t.aggregated_deduct < 0) {
        themeDisplayName += ` [${t.aggregated_deduct}分]`
      }
      tnodes.push({ id: t.id, name: themeDisplayName, raw_name: t.name, type: 'theme', children: [] })
    }
    // 为维度构建显示名称，包含聚合分数
    let dimDisplayName = d.name
    if (d.aggregated_weight !== undefined && d.aggregated_weight > 0) {
      dimDisplayName += ` (${d.aggregated_weight}分)`
    }
    if (d.aggregated_deduct !== undefined && d.aggregated_deduct < 0) {
      dimDisplayName += ` [${d.aggregated_deduct}分]`
    }
    nodes.push({ id: d.id, name: dimDisplayName, raw_name: d.name, type: 'dimension', children: tnodes })
  }
  tree.value = nodes
  applyFilter()
}

function applyFilter() {
  const kw = keyword.value.trim()
  if (!kw) return
  // 使用raw_name进行搜索，因为name包含了分数显示
  const match = (n: any) => (n.raw_name || n.name)?.includes(kw)
  const filterNodes = (nodes: any[]) => nodes.map(n => ({ ...n, children: filterNodes(n.children||[]) })).filter(n => match(n) || (n.children && n.children.length))
  tree.value = filterNodes(tree.value)
}

function onNodeClick(node: any) {
  if (node.type === 'dimension') {
    selectedDimensionId.value = node.id
    selectedThemeId.value = ''
  } else if (node.type === 'theme') {
    selectedThemeId.value = node.id
    loadItems(node.id)
  }
}

function openEditFromNode(node: any) {
  if (node.type === 'dimension') {
    selectedDimensionId.value = node.id
    dimensionEditName.value = node.raw_name || node.name
    showDimensionEditDialog.value = true
  } else if (node.type === 'theme') {
    selectedThemeId.value = node.id
    themeEditName.value = node.raw_name || node.name
    showThemeEditDialog.value = true
  }
}

async function loadItems(themeId: string) {
  const resp = await api.get('/indicators/items', { params: { theme_id: themeId } })
  items.value = resp.data.sort((a: any,b: any)=>a.order_index-b.order_index)
}

function allowDrop(draggingNode: any, dropNode: any, type: string) {
  if (draggingNode?.data?.type !== dropNode?.data?.type) return false
  return type === 'inner' ? false : true
}

async function onNodeDrop(draggingNode: any, dropNode: any) {
  if (draggingNode?.data?.type === 'dimension') {
    const ids = tree.value.map((n: any)=>n.id)
    await api.patch('/indicators/dimensions/order', { version_id: currentVersionId.value, ids })
    await reloadTree()
  }
  if (draggingNode?.data?.type === 'theme') {
    const parent = tree.value.find((n: any)=>n.children.some((c:any)=>c.id===draggingNode.data.id))
    const ids = parent.children.map((c: any)=>c.id)
    await api.patch(`/indicators/themes/${parent.id}/order`, ids)
    await reloadTree()
  }
}

function openUploadDialog() { showUploadDialog.value = true }
function onFileChange(e: Event) {
  const input = e.target as HTMLInputElement
  uploadFile.value = (input.files && input.files[0]) ? input.files[0] : null
}
async function confirmUpload() {
  if (!currentVersionId.value || !uploadFile.value) return
  
  console.log('开始上传流程测试...')
  
  // 首先测试简单端点
  try {
    console.log('测试后端连接...')
    const testResponse = await api.post('/indicators/import/test')
    console.log('测试端点响应:', testResponse.data)
  } catch (testError: any) {
    console.error('测试端点失败:', {
      message: testError.message,
      response: testError.response?.data,
      status: testError.response?.status
    })
    return
  }
  
  // 如果测试通过，进行实际上传
  const fd = new FormData()
  fd.append('file', uploadFile.value)
  fd.append('version_id', currentVersionId.value)
  fd.append('dry_run', 'false')
  const token = localStorage.getItem('token') || ''
  
  console.log('准备上传文件:', {
    url: '/indicators/import/upload',
    version_id: currentVersionId.value,
    file: uploadFile.value.name,
    token: token ? '已设置' : '未设置'
  })
  
  try {
    const response = await api.post('/indicators/import/upload', fd, { 
      headers: { 
        'Content-Type': 'multipart/form-data', 
        ...(token ? { Authorization: `Bearer ${token}` } : {}) 
      } 
    })
    console.log('上传成功:', response.data)
    showUploadDialog.value = false
    uploadFile.value = null
    await reloadTree()
  } catch (error: any) {
    console.error('上传失败:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      headers: error.response?.headers
    })
    throw error
  }
}

async function allocateCodesForTheme() {
  if (!selectedThemeId.value) return
  const need = items.value.filter(i => !i.code).length
  if (!need) return
  const resp = await api.post('/indicators/items/codes/allocate', null, { params: { count: need } })
  const codes: string[] = resp.data.codes
  let idx = 0
  for (const i of items.value) {
    if (!i.code) { i.code = codes[idx++].toUpperCase() }
  }
}

async function allocateCodeForItem(row: Item) {
  const resp = await api.post(`/indicators/items/${row.id}/code`)
  row.code = resp.data.code.toUpperCase()
}

async function saveItemEdits() {
  if (!selectedThemeId.value) return
  saving.value = true
  try {
    for (const i of items.value) {
      await api.patch(`/indicators/item/${i.id}`, { name: i.name, category: i.category, weight: i.weight, deduct_value: i.deduct_value, veto_flag: i.veto_flag, order_index: i.order_index, code: i.code, criteria: i.criteria })
    }
  } finally { saving.value = false }
}

async function saveDimensionName() {
  if (!selectedDimensionId.value) return
  await api.patch(`/indicators/dimension/${selectedDimensionId.value}`, { name: dimensionEditName.value })
  showDimensionEditDialog.value = false
  await reloadTree()
}

async function saveThemeName() {
  if (!selectedThemeId.value) return
  await api.patch(`/indicators/theme/${selectedThemeId.value}`, { name: themeEditName.value })
  showThemeEditDialog.value = false
  await reloadTree()
}

onMounted(async () => {
  // 加载活动类型字典
  try {
    const resp = await api.get('/dictionaries/items', { params: { type_code: 'activity_type', page_size: 100 } })
    activityTypeOptions.value = resp.data
  } catch {}
  await loadVersions(); await reloadTree()
})
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; }
.toolbar { display: flex; align-items: center; }
.filters { flex: 1; display: flex; align-items: center; gap: 12px; }
.version-summary { margin-top: 6px; display: grid; grid-template-columns: auto 1fr; row-gap: 4px; column-gap: 8px; align-items: center; }
.vs-row { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.vs-label { color: #606266; }
.vs-name { font-weight: 600; color: #303133; }
.vs-code { color: #909399; }
.vs-empty { color: #c0c4cc; }
.content { flex: 1; display: flex; min-height: 0; gap: 12px; }
.left { width: 320px; border-right: 1px solid #eee; padding-right: 12px; overflow: auto; }
.right { flex: 1; min-width: 0; }
.table-toolbar { display: flex; gap: 8px; margin-bottom: 8px; }
.placeholder { color: #909399; padding: 16px; }
</style>
